package com.zb.response;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class ResponseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String contextPath = "/Users/juzi/Documents/idea-Workspace/MyResource/java-web-servlet/response/src/main/resources/张彬.png";
        System.out.println(contextPath);
        String fileName = contextPath.substring(contextPath.lastIndexOf("/") + 1);
        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        FileInputStream fis = new FileInputStream(contextPath);
        int len = 0;
        byte[] buffer = new byte[1024];
        ServletOutputStream os = resp.getOutputStream();
        while ((len = fis.read(buffer)) != -1){
            os.write(buffer, 0, len);
        }

        fis.close();
        os.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
